const jwt = require('jwt-simple')

const secret = 'asd;lfkjaklsdfjaklsdfjaklsdfjaklsdjfla;sdkjfaklsfnqw8947124ujksldfu9hfsdjhkajsdfhi1y34iu'

module.exports = {
  // 生成 token
  genToken(payload) {
    return jwt.encode(payload, secret)
  },
  // 校验 token
  verifyToken(token) {
    try {
      const payload = jwt.decode(token, secret)
      return payload
    } catch (error) {
      const err = new Error()
      if (error.message === 'Not enough or too many segments') {
        err.data = {
          code: 4002,
          data: {
            message: 'token 数据格式有误'
          }
        }
      } else if (error.message === 'Signature verification failed') {
        err.data = {
          code: 4003,
          data: {
            message: 'token 签名有误'
          }
        }
      } else if (error.message === 'Token expired') {
        err.data = {
          code: 4004,
          data: {
            message: 'token 已过期'
          }
        }
      } else {
        err.data = {
          code: 4005,
          data: {
            message: 'token验证失败'
          }
        }
      }
      
      throw err
    }
  }
}